﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Actions
{
    public class SetDefaultValueAction : Action
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SetDefaultValueAction"/> class.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="propertyName">The name of the property.</param>
        public SetDefaultValueAction(IFrameXmlControl control, string propertyName)
            : base(control)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            this.PropertyName = propertyName;
        }

        /// <summary>
        /// Gets a value indicating whether this action is available.
        /// </summary>
        /// <value></value>
        public override bool IsAvailable
        {
            get
            {
                PropertyInfo propertyInfo = SerializationObject.GetType().GetProperty(PropertyName);
                if (propertyInfo != null)
                    return propertyInfo.GetValue(SerializationObject, null) == null;

                return false;
            }
        }
        /// <summary>
        /// Gets or sets the name of the action.
        /// </summary>
        /// <value></value>
        public override string DisplayName
        {
            get
            {
                return "Add " + PropertyName;
            }
        }

        /// <summary>
        /// Gets or sets the property's name that should be set.
        /// </summary>
        public string PropertyName { get; private set; }

        /// <summary>
        /// Gets or sets the default value.
        /// </summary>
        public ICloneable DefaultValue { get; set; }

        /// <summary>
        /// Invokes the action.
        /// </summary>
        public override void Invoke()
        {
            var propertyDescriptor = TypeDescriptor.GetProperties(this.Control).Find(this.PropertyName, false);
            if (propertyDescriptor != null)
            {
                object oldValue = propertyDescriptor.GetValue(this.Control);
                object value;

                if (this.DefaultValue != null)
                    value = this.DefaultValue.Clone();
                else
                    value = Activator.CreateInstance(propertyDescriptor.PropertyType);

                propertyDescriptor.SetValue(this.Control, value);

                RaiseComponentChanged(propertyDescriptor, oldValue, value);
            }
        }
    }
}